package com.example.sunmiv1.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.RepayAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.dialog.RepayDialog;
import com.example.sunmiv1.dialog.SetCreditMoneyDialog;
import com.example.sunmiv1.entity.UserRepaymentInfo;
import com.example.sunmiv1.utils.MathUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RepayActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.repay_listView)
    PullToRefreshListView repayListView;
    @BindView(R.id.repay_money)
    TextView repayMoney;
    @BindView(R.id.repay_custom)
    TextView repayCustom;
    @BindView(R.id.repay_confirm)
    TextView repayConfirm;

    private LoadingDialog loadingDialog;
    private int page = 1;
    private Context context;
    private UserRepaymentInfo userRepaymentInfo;
    private List<UserRepaymentInfo.DataBean.ListBean> list = new ArrayList<>();
    private RepayAdapter repayAdapter;
    private double totalMoney = 0;
    private String creditMoney;
    private String vid = "";
    private ACache aCache;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    list.addAll(userRepaymentInfo.getData().getList());
                    creditMoney = "0";
                    double m = 0;
                    for (int i = 0; i < list.size(); i++) {
                        m = MathUtil.add(m, Double.parseDouble(list.get(i).getMoney()));
                    }
                    creditMoney = m + "";
                    setRepayAdapter();
                    break;
                case 2:
                    break;
            }
        }
    };


    @Override
    protected void initView() {
        setContentView(R.layout.activity_repay);
        ButterKnife.bind(this);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(this);
        titleTitle.setText(R.string.repayTitle);
    }

    @Override
    protected void initData() {
        creditMoney = getIntent().getStringExtra("creditMoney");
        vid = getIntent().getStringExtra("vid");
        getUserArrearage();
    }

    @Override
    protected void initListener() {
        repayListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                setRepayAdapter();
                getUserArrearage();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                getUserArrearage();
            }
        });
    }


    @OnClick({R.id.title_back, R.id.repay_custom, R.id.repay_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.repay_custom:
                JSONArray jsonArray = new JSONArray();
                jsonArray.put(creditMoney);
                SetCreditMoneyDialog.newInstance(jsonArray, 3)
                        .callback(o -> {
                            totalMoney = Double.parseDouble(o.toString());
                            repayMoney.setText("$" + totalMoney);
                            double creditMoney = Double.parseDouble(o.toString());
                            for (UserRepaymentInfo.DataBean.ListBean bean : list) {
                                creditMoney = MathUtil.sub(creditMoney, Double.parseDouble(bean.getMoney()));
                                if (creditMoney >= 0) {
                                    bean.setCustomMoney(bean.getMoney());
                                    bean.setCheck(true);
                                } else if (MathUtil.add(Double.parseDouble(bean.getMoney()), creditMoney) != 0) {
                                    bean.setCustomMoney(MathUtil.add(Double.parseDouble(bean.getMoney()), creditMoney) + "");
                                    if (MathUtil.add(Double.parseDouble(bean.getMoney()), creditMoney) != 0) {
                                        bean.setCheck(true);
                                    }
                                    break;
                                }
                            }
                            repayAdapter.setCheckFlag(true);
                        })
                        .startShow(getSupportFragmentManager(), "")
                        .setCancelable(false);
                break;
            case R.id.repay_confirm:
                int size = 0;
                for (int i = 0; i < list.size(); i++) {
                    UserRepaymentInfo.DataBean.ListBean bean = list.get(i);
                    if (bean.isCheck()) {
                        if (TextUtils.isEmpty(bean.getRepaymentMoney()) || Double.parseDouble(bean.getRepaymentMoney()) == 0) {
                            Toast.makeText(context, "請輸入第" + (i + 1) + "條的還款金額", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (Double.parseDouble(bean.getRepaymentMoney()) > Double.parseDouble(bean.getMoney())) {
                            Toast.makeText(context, "還款金額不能大於賒賬金額", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        size++;
                    }
                }
                if (size == 0) {
                    Toast.makeText(context, "請先選擇要還款的訂單", Toast.LENGTH_SHORT).show();
                    return;
                }
                RepayDialog.newInstance(totalMoney, vid, list)
                        .callback(o -> {
                            page = 1;
                            list.clear();
                            setRepayAdapter();
                            getUserArrearage();
                        })
                        .startShow(getSupportFragmentManager(), "")
                        .setCancelable(false);
                break;
        }
    }


    private void setRepayAdapter() {
        if (repayAdapter == null) {
            repayAdapter = new RepayAdapter(list);
            repayListView.setAdapter(repayAdapter);
        } else {
            repayAdapter.notifyDataSetChanged();
        }
        repayAdapter.setCallBack(() -> {
            totalMoney = 0;
            for (UserRepaymentInfo.DataBean.ListBean bean : list) {
                if (bean.isCheck()) {
                    if (!TextUtils.isEmpty(bean.getRepaymentMoney()) && Double.parseDouble(bean.getRepaymentMoney()) != 0) {
                        totalMoney = MathUtil.add(totalMoney, Double.parseDouble(bean.getRepaymentMoney()));
                    }
                }
            }
            repayMoney.setText("$" + totalMoney);
        });
    }

    /**
     * 獲取用戶賒賬記錄
     */
    private void getUserArrearage() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("credit_id", getIntent().getStringExtra("id"));
            jsonObject.put("page", page);
            jsonObject.put("limit", "20");
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            } else {
                jsonObject.put("editor_type", "2");
            }
            jsonObject.put("order_no", "");
            jsonObject.put("start_time", "");
            jsonObject.put("end_time", "");
            jsonObject.put("state", "");//還款狀態 1已還清 2未還清
            jsonObject.put("searchText", "");//用戶暱稱、姓名、手機號(搜索)
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_USER_ARREARAGE, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                repayListView.onRefreshComplete();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        totalMoney = 0;
                        repayMoney.setText("$" + totalMoney);
                        if (repayAdapter != null) {
                            repayAdapter.setCheckFlag(false);
                        }
                        userRepaymentInfo = GsonUtils.JsonToBean(text, UserRepaymentInfo.class);
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                repayListView.onRefreshComplete();
            }
        });
    }


}
